<template>
	<view class="content">
		<view class="navbar">
			<view v-for="(item, index) in navList" :key="index" class="nav-item" :class="{ current: tabCurrentIndex === index }" @click="tabClick(index)">{{ item.text }}</view>
		</view>

		<swiper :current="tabCurrentIndex" class="swiper-box" duration="300" @change="changeTab">
			<swiper-item class="tab-content" v-for="(tabItem, tabIndex) in navList" :key="tabIndex">
				<scroll-view class="list-scroll-content" scroll-y @scrolltolower="loadData">
					<!-- 空白页 -->
					<empty v-if="tabItem.loaded === true && tabItem.orderLists.length === 0"></empty>

					<!-- 订单列表 -->

					<view class="list" v-for="(item, index) in tabItem.orderLists" :key="index" >
						<uni-list >
							<uni-list-item title="订单号" :note="item.order_number" :show-arrow="false">
								<template v-slot:right="">
									<text style="color: red;font-size: 24rpx;">{{getStatusText(item.status)}}</text>
								</template>
							</uni-list-item>
						</uni-list>
						<my-card
							v-for="(goods, goodsId) in item.orderItems"
							class="goods"
							:idid="goodsId"
							:quantity="goods.quantity"
							:price="goods.price"
							desc=""
							:title="goods.title"
							:thumb="goods.image"
							@click.native="toOrderView(index)"
						>
						<view slot="footer" class="footer">
							<button v-if="item.status == 40" @click.stop.native="serviceAddView(goods.id)">申请售后</button>
							<button v-if="item.status == 40 && goods.has_evaluate == 0"  @click.stop.native="evaluateAddView(goods.id)">评价</button>
							<button v-else-if="item.status == 40 && goods.has_evaluate == 1" disabled>已评价</button>
						</view>
						</my-card>

						<view class="total">
							合计:￥ {{ item.total / 1 + item.shipping_fee / 1 }}
							<text>（免运费）</text>
						</view>

						<view class="order-footer">
							<template v-if="item.status === 10">
								<view class="order-footer-btns">
									<button size="mini" @click="delOrder(index)">删除订单</button>
									
									<!-- #ifdef H5 -->
									<button size="mini" type="warn" class="pay" @click="payH5(index)">立即支付</button>
									<!-- #endif -->
									
									<!-- #ifdef MP-WEIXIN -->
									<button size="mini" type="warn" class="pay" @click="pay(index)">立即支付</button>
									<!-- #endif -->									
									 
								</view>
								
							</template>						
							<template v-if="item.status === 30">
								<view class="order-footer-btns">
									<button size="mini" @click="orderTracker(index)">查看物流</button>
									<button size="mini" type="warn" @click="confirmOrder(index)">确认收货</button>
								</view>
							</template>
						</view>
					</view>

					<!-- 订单列表end -->

					<uni-load-more :status="tabItem.loadingType"></uni-load-more>
				</scroll-view>
			</swiper-item>
		</swiper>
	</view>
</template>

<script>
import uniList from '@/components/uni-list/uni-list.vue';
import uniListItem from '@/components/uni-list-item/uni-list-item.vue';
import myCard from '@/components/my-card/my-card.vue';

import uniLoadMore from '@/components/uni-load-more/uni-load-more.vue';
import empty from '@/components/empty';


const STATUS_TEXT = {
  10: "待付款",
  20: "待发货",
  30: "待收货",
  40: "已完成",
};


export default {
	components: {
		uniList,
		uniListItem,
		myCard,
		uniLoadMore,
		empty
	},

	data() {
		return {
			tabCurrentIndex: 0,
			navList: [
				{
					state: 0,
					page: 1,
					text: '全部',
					loadingType: 'more',
					orderLists: []
				},
				{
					state: 10,
					page: 1,
					text: '待付款',
					loadingType: 'more',
					orderLists: []
				},
				{
					state: 20,
					page: 1,
					text: '待收货',
					loadingType: 'more',
					orderLists: []
				},
				{
					state: 30,
					page: 1,
					text: '待收货',
					loadingType: 'more',
					orderLists: []
				},
				{
					state: 40,
					page: 1,
					text: '已完成',
					loadingType: 'more',
					orderLists: []
				}
			]
		};
	},
	onLoad(options) {
		/**
		 * 修复app端点击除全部订单外的按钮进入时不加载数据的问题
		 * 替换onLoad下代码即可
		 */
		this.tabCurrentIndex = +options.state;
		// #ifndef MP
		this.loadData();
		// #endif
		// #ifdef MP
		if (options.state == 0) {
			this.loadData();
		}
		// #endif
		
		
		let that = this;
		this.$EventBus.$on('evaluate_add_success', function(val) {
		  if (val === 'ok') {
			  that.navList[that.tabCurrentIndex].page = 1
			  that.navList[that.tabCurrentIndex].orderLists.length= 0
			  that.loadData();
		  }
		});
		
	},
	
	 
	methods: {
		
		
		
		// #ifdef MP-WEIXIN
		// 微信小程序支付			
		pay(index){
			
			
			let order_id = this.navList[this.tabCurrentIndex].orderLists[index].id
			
			this.$http.post('/shop.order/wx_app_pay_sign', { order_id: order_id }).then(res => {
			
			   console.log(JSON.stringify(res));
			   				
			   if (res.data.data) {
			   	//this.jsApiCall(res.data);				
				
				
					uni.requestPayment({
						provider: 'wxpay',
						timeStamp: res.data.data.timeStamp,
						nonceStr: res.data.data.nonceStr,
						package: res.data.data.package,
						signType: "MD5",
						paySign: res.data.data.paySign,							
						success: function(Pay_res) {
							
							uni.showModal({
								    content: '支付成功',
									showCancel: false,
								    success: function (res) {
								        if (res.confirm) {
								            //console.log('用户点击确定');
											// 点击 确定 进入订单
											uni.navigateTo({
												url: './order?state=0'
											})
								        } 
								    }
							})		
							
							 
					
						},
						fail: function(err) {
							console.log('fail:' + JSON.stringify(err));
						}
					});
				
				
			   } else {
			   	alert('支付出现一些问题，请联系管理员');
			   }
			
			 });				
		},
		
		// #endif
		
		
		// #ifdef H5
		// 微信H5支付
		
		// 调用微信WeixinJSBridge支付
		jsApiCall(signature) {
			/* eslint-disable no-undef */
			WeixinJSBridge.invoke('getBrandWCPayRequest', signature, function(res) {
				// WeixinJSBridge.log(res.err_msg);			
				// alert(JSON.stringify(res));
		
				if (res.err_msg === 'get_brand_wcpay_request:ok') {
		
					uni.showModal({
						    content: '支付成功',
							showCancel: false,
						    success: function (res) {
						        if (res.confirm) {
						            //console.log('用户点击确定');
									// 点击 确定 进入订单
									uni.navigateTo({
										url: './order?state=0'
									})
						        } 
						    }
					})				
		
				} else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
					alert('用户取消支付');
				} else {
					alert('支付失败');
				}
			});
		},
		
		payH5(index){
			
			let order_id = this.navList[this.tabCurrentIndex].orderLists[index].id
			
			this.$http.post('/shop.order/wx_pay_sign', { order_id: order_id }).then(res => {
			
			   console.log(JSON.stringify(res));				   				
			   if (res.data.data) {
				   
					this.jsApiCall(res.data.data);									
				
			   } else {
					alert('支付出现一些问题，请联系管理员');
			   }
			
			 });
			
		},		
		
		// #endif


		// 确认订单
		confirmOrder(index) {
			
			let order_id = this.navList[this.tabCurrentIndex].orderLists[index].id
			
			
			let that = this
			
			uni.showModal({
				 title: '提示',
				    content: '确定要删除该订单吗',
				    success: function (res) {
				        if (res.confirm) {
							
				            
							// 请求服务器
							that.$http.post('/shop.order/complete', {
							  order_id: order_id
							}).then(res => {		
							
							   if (res.data.data > 0) {			   
								   
								   that.navList[that.tabCurrentIndex].orderLists[index].status = 40				   
								   uni.showToast({
								   	title: '已确认收货'
								   })				    
							   }		
							});
							
							
				        } else if (res.cancel) {
				            // console.log('用户点击取消');
				        }
				    }
			})
			
			
			
		},

		
		// 申请售后
		serviceAddView(order_goods_id) {
		
			uni.navigateTo({
				url:'./serviceAddView?order_goods_id=' + order_goods_id 
			})			 
		
		},
		
		
		
		// 评价
		evaluateAddView(order_goods_id) {
			
			uni.navigateTo({
				url:'./evaluateAddView?order_goods_id=' + order_goods_id
			})		
			 
		
		},

		// 物流信息
		orderTracker(index) {
			
			let order_id = this.navList[this.tabCurrentIndex].orderLists[index].id
			
			uni.navigateTo({
				url: './orderTracker?order_id=' + order_id
			})
			
		},

		// 订单查看
		toOrderView(index) {
			
		 
		  
			  let order_id = this.navList[this.tabCurrentIndex].orderLists[index].id
			  
			  console.log(order_id)
			  
			  uni.navigateTo({
			  	url:'./orderView?order_id=' + order_id
			  }) 
		 
			
			
		},

		getStatusText(status) {
		  return STATUS_TEXT[status] || "";
		},

		// 删除订单
		delOrder(index) {
			
			
			let that = this;
			
			let order_id = this.navList[this.tabCurrentIndex].orderLists[index].id;

			uni.showModal({
				 title: '提示',
				    content: '确定要删除该订单吗',
				    success: function (res) {
				        if (res.confirm) {
							
				            
							that.$http.post('/shop.order/delete', {
							  order_id: order_id
							}).then(res => {
							
							   if (res.data.data > 0) {
							     that.navList[that.tabCurrentIndex].orderLists.splice(index, 1);
								 uni.showToast({
									 icon:"none",
								 	title:"已删除该订单"
								 })
							     
							   }
							
							});
							
							
				        } else if (res.cancel) {
				            // console.log('用户点击取消');
				        }
				    }
			})

		 
 
		},


		//获取订单列表
		loadData(source) {
			//这里是将订单挂载到tab列表下
			let index = this.tabCurrentIndex;
			let navItem = this.navList[index];
			let state = navItem.state;
			let page = navItem.page;

			if (source === 'tabChange' && navItem.loaded === true) {
				//tab切换只有第一次需要加载数据
				return;
			}
			if (navItem.loadingType === 'loading') {
				//防止重复加载
				return;
			}

			navItem.loadingType = 'loading';

			this.$http
				.post('/shop.order/lists', {
					page_size: 10,
					page: navItem.page,
					status: state
				})
				.then(res => {
					navItem.orderLists.push(...(res.data.data || []));

					

					//loaded新字段用于表示数据加载完毕，如果为空可以显示空白页
					this.$set(navItem, 'loaded', true);
					
					
					console.log("navItem.page" + navItem.page)
					
					if (res.data.data.length === 0) {
						//判断是否还有数据， 有改为 more， 没有改为noMore
						navItem.loadingType = 'noMore';
					}else if(navItem.page === 1 && res.data.data.length <10){
						navItem.loadingType = 'noMore';
					} else {
						//判断是否还有数据， 有改为 more， 没有改为noMore
						navItem.loadingType = 'more';
					}

					// 下一页
					navItem.page++;
				});
		},

		//swiper 切换
		changeTab(e) {
			this.tabCurrentIndex = e.target.current;
			this.loadData('tabChange');
		},

		//顶部tab点击
		tabClick(index) {
			this.tabCurrentIndex = index;
		},

		initData() {}
	}
};
</script>

<style lang="scss">
page,
.content {
	height: 100%;
}

.list {
	background-color: #ffffff;
	margin-bottom: 20rpx;
	.total {
		padding: 20rpx;
		text-align: right;
	}
	.order-footer {	
		.order-footer-btns{
			padding-bottom: 20rpx;
			text-align: right;
			button {
				margin-right: 20rpx;
			}
		}
	}
}

.swiper-box {
	height: calc(100% - 40px);
}
.list-scroll-content {
	height: 100%;
}


.footer{
	display: flex;
	padding-top: 10rpx;
	padding-bottom: 10rpx;
	button{
		margin-left: 10rpx;
		font-size: 20rpx;
		border: 0;
		border-radius: 0;
	}
}

.navbar {
	display: flex;
	height: 40px;
	padding: 0 5px;
	background: #fff;
	box-shadow: 0 1px 5px rgba(0, 0, 0, 0.06);
	position: relative;
	z-index: 10;
	.nav-item {
		flex: 1;
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100%;
		font-size: 15px;
		color: #000000;
		position: relative;
		&.current {
			color: $colorPrimary;
			&:after {
				content: '';
				position: absolute;
				left: 50%;
				bottom: 0;
				transform: translateX(-50%);
				width: 44px;
				height: 0;
				border-bottom: 2px solid $colorPrimary;
			}
		}
	}
}

/* load-more */
.uni-load-more {
	display: flex;
	flex-direction: row;
	height: 80upx;
	align-items: center;
	justify-content: center;
}

.uni-load-more__text {
	font-size: 28upx;
	color: #999;
}

.uni-load-more__img {
	height: 24px;
	width: 24px;
	margin-right: 10px;
}

.uni-load-more__img > view {
	position: absolute;
}

.uni-load-more__img > view view {
	width: 6px;
	height: 2px;
	border-top-left-radius: 1px;
	border-bottom-left-radius: 1px;
	background: #999;
	position: absolute;
	opacity: 0.2;
	transform-origin: 50%;
	animation: load 1.56s ease infinite;
}

.uni-load-more__img > view view:nth-child(1) {
	transform: rotate(90deg);
	top: 2px;
	left: 9px;
}

.uni-load-more__img > view view:nth-child(2) {
	transform: rotate(180deg);
	top: 11px;
	right: 0;
}

.uni-load-more__img > view view:nth-child(3) {
	transform: rotate(270deg);
	bottom: 2px;
	left: 9px;
}

.uni-load-more__img > view view:nth-child(4) {
	top: 11px;
	left: 0;
}
</style>
